# -*- encoding: utf-8 -*-
from django.shortcuts import render_to_response
from django.shortcuts import redirect
from django.http import HttpResponse
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import logout
from idit.account.forms import SignupForm, EditPasswordForm, AccountForm
from django.template import RequestContext

def logout_view(req):
    logout(req)
    return redirect('home')
    
def signup(req):
    """
注册页面
    """
    if req.user.is_active :
        return redirect('home')
    if req.method == 'POST':
        form = SignupForm(req.POST)
        if form.is_valid():
            cd = form.cleaned_data
            email = cd['email']
            password = cd['password']
            nickname = cd['nickname']
            user = User.objects.create_user(username=email, password=password, email=email)
            user.is_staff = True
            user.save()
            profile = user.get_profile()
            profile.nickname = nickname
            profile.save()
            req.user = user
            return redirect('home')
    else:
        form = SignupForm()
    return render_to_response('account/signup.html', {'form':form},context_instance=RequestContext(req))

@login_required
def edit_password(req):
    """
修改密码页面
    """
    if req.POST:
        form = EditPasswordForm(req.POST)
        if form.is_valid():
            cd = form.cleaned_data
            newpassword = cd['newpassword']
            req.user.set_password(newpassword)
            req.user.save()
            return redirect(profile)
    else:
        form = EditPasswordForm()
    return render_to_response('account/edit_password.html', {'form':form},context_instance=RequestContext(req))
    
@login_required
def reset_password(req):
    return redirect('home')


@login_required
def profile(req):
    if req.POST:
        form = AccountForm(req.POST)
        if form.is_valid():
            cd = form.cleaned_data
            nickname = cd['nickname']
            userprofile = req.user.userprofile
            userprofile.nickname = nickname
            userprofile.save()
    else:
        form = AccountForm({'nickname':req.user.userprofile.nickname})
    return render_to_response('account/profile.html', {'form':form},context_instance=RequestContext(req))

